package cn.wolfcode.luowowo.mgrsite.listener;

import cn.wolfcode.luowowo.article.domain.Destination;
import cn.wolfcode.luowowo.article.domain.StrategyDetail;
import cn.wolfcode.luowowo.article.service.IStrategyDetailService;
import cn.wolfcode.luowowo.cache.key.RedisKey;
import cn.wolfcode.luowowo.cache.service.IStrategyStatsCacheService;
import cn.wolfcode.luowowo.cache.vo.StrategyStats;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class StrategyDetailHotDataListener implements ApplicationListener<ContextRefreshedEvent> {

    @Value("${hotData.init}")
    private Boolean flag;

    @Reference
    private IStrategyDetailService detailService;
    @Reference
    private IStrategyStatsCacheService strategyStatsCacheService;

    public void onApplicationEvent(ContextRefreshedEvent event) {
        System.err.println(detailService.getClass());
        if (flag) {
            System.out.println("服务器初始化");
            //1.数据从Mysql中查询出来.
            List<StrategyDetail> details = detailService.list();
            for (StrategyDetail detail : details) {
                Long id = detail.getId();
                if (strategyStatsCacheService.noExist(id)) {
                    //2.封装统计对象
                    Destination dest = detail.getDest();
                    StrategyStats stats = new StrategyStats();
                    stats.setStrategyId(detail.getId());
                    stats.setDestId(dest.getId());
                    stats.setDestName(dest.getName());
                    stats.setTitle(detail.getTitle());

                    stats.setViewnum(detail.getViewnum());
                    stats.setFavornum(detail.getFavornum());
                    stats.setReplynum(detail.getReplynum());
                    stats.setSharenum(detail.getSharenum());
                    stats.setThumbsupnum(detail.getThumbsupnum());
                    //保存redis
                    strategyStatsCacheService.setStrategyStats(stats);
                }

                //排行榜数据初始化(把数据从mysql中迁移到redis(zset的数据格式,方便排序))
                //飙升统计排序
                if(strategyStatsCacheService.noExistRank(RedisKey.STRATEGY_STATS_UP_SORT,id)){
                    int num = detail.getViewnum() + detail.getReplynum();
                    strategyStatsCacheService.addRank(RedisKey.STRATEGY_STATS_UP_SORT,num,id);
                }
                //热门统计排序
                if(strategyStatsCacheService.noExistRank(RedisKey.STRATEGY_STATS_HOT_SORT,id)){
                    int num = detail.getViewnum() + detail.getReplynum();
                    strategyStatsCacheService.addRank(RedisKey.STRATEGY_STATS_HOT_SORT,num,id);
                }
            }

        }

    }
}
